package com.dailyblue.project.estate.owner.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.project.estate.commons.bean.Owner;
import com.dailyblue.project.estate.commons.handler.OwnerException;
import com.dailyblue.project.estate.commons.mapper.OwnerMapper;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.ResultTool;
import com.dailyblue.project.estate.owner.service.OwnerService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class OwnerServiceImpl extends ServiceImpl<OwnerMapper, Owner> implements OwnerService {
    @Resource
    private OwnerMapper ownerMapper;

    @Override
    public JsonResult addOwner(Owner owner) {
        boolean b = save(owner);
        if (!b) {
           throw new OwnerException("添加失败");
        }
        return ResultTool.success("success");
    }


    public JsonResult<Owner> findOwnerById(String id) {
        log.info("id:{}",id);
        Owner owner = getById(id);
        return ResultTool.success(owner);
    }

    @Cacheable(cacheNames = "findOwnerById")
    public JsonResult findAllOwners() {
        List<Owner> list = list();
        return ResultTool.success(list);
    }

    @CacheEvict(cacheNames = "findOwnerById")
    public JsonResult deleteOwner(String id) {
        boolean b = removeById(id);
        if (!b) {
            return ResultTool.fail(201, "删除失败");
        }
        return ResultTool.success("删除成功");
    }

    @CacheEvict(cacheNames = "findOwnerById")
    public JsonResult updateOwner(Owner owner) {
        UpdateWrapper<Owner> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", owner.getId());
        updateWrapper.set("community_id", owner.getCommunityId());
        updateWrapper.set("house_id", owner.getHouseId());
        updateWrapper.set("name", owner.getName());
        updateWrapper.set("picture", owner.getPicture());
        updateWrapper.set("idcard", owner.getIdcard());
        updateWrapper.set("telephone", owner.getTelephone());
        updateWrapper.set("profession", owner.getProfession());
        updateWrapper.set("sex", owner.getSex());
        updateWrapper.set("type", owner.getType());
        updateWrapper.set("remark", owner.getRemark());
        updateWrapper.set("update_time", owner.getUpdateTime());
        updateWrapper.set("birthday", owner.getBirthday());
        int i = ownerMapper.update(updateWrapper);
        if (i <= 0) {
            return ResultTool.fail(201, "更新失败");
        }
        return ResultTool.success("更新成功");
    }
}
